import { useState, useEffect } from 'react';
import { Form, Table, Row, Col, Button, Input, Pagination, } from 'antd';
import InfiniteScroll from 'react-infinite-scroller';
import styles from './style.less';
import { axconst } from '@/shared/axconst';
import AxModal from '@/components/AxForm/AxModal/index';
import { AxInput } from '../AxFormItem/AxInput';
import AxColumnEnum from '@/components/AxList/AxColumnEnum';

const { Search } = Input;
/**
 * 自定义选择缴费人
 * @param title 表单名称
 * @param searchField 查询字段（默认值name）
 * @param searchValue 查询内容
 * @param placeholder 占位符
 * @param autoSelect 当只有一条数据时，自动选中
 * @param visible 可见性
 * @param handleVisible 可见性处理函数
 * @param handleRead 选项数据读取函数
 * @param handleCreate 添加处理函数
 * @param handleSelect 选择处理函数
 */
const AxSelectPayer = props => {
  const {
    form,
    searchField = 'name',
    searchValue,
    placeholder,
    autoSelect = false,
    handleRead: handleReadFromProps,
    handleCreate: handleCreateFromProps,
    handleSelect,
    handleVisible,
    ...rest
  } = props;
  const [data, setData] = useState({
    list: [],
    pagination: {},
  });
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  /** 查询字段 */
  let field = {};
  /** 分页初始值 */
  let page = axconst.page.params;

  useEffect(() => {
    if (searchValue && searchValue.trim() !== '') handleSearch(searchValue.trim());
    else setVisible(true);
  }, [searchValue]);

  /** 点击行选中 */
  const handleClickRow = (record) => {
    if (handleSelect) handleSelect({ value: record.id, text: record.name });
    if (handleVisible) handleVisible();
  };

  /** 搜索 */
  const handleSearch = val => {
    if (val && val.trim() !== '') {
      field[searchField] = val.trim();
    } else {
      field = {};
    }
    return handleRead();
  };

  /** 读取数据 */
  const handleRead = () => {
    if (handleReadFromProps) {
      setLoading(true);
      return handleReadFromProps(page, field).then((res) => {
        if (autoSelect === true && res.list.length === 1) {
          handleClickRow(res.list[0]);
        }
        else {
          setData(res);
          setLoading(false);
          setVisible(true);
        }
      });
    }
  };

  /** 保存数据 */
  const handleCreate = () => {
    if (handleCreateFromProps)
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        setConfirmLoading(true);

        handleCreateFromProps(fieldsValue).then(() => {
          if (handleVisible) handleVisible();
        }).catch(() => {
          setConfirmLoading(false);
        });
      });
  };
  /** 重置 */
  const handleReset = () => {
    form.resetFields();
  };

  /** 改变分页 */
  const handlePageChange = (currentPage, pageSize) => {
    page = {
      currentPage,
      pageSize,
    };
    handleRead();
  };

  /** 待选列 */
  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: axconst.width.threeonly,
      ellipsis: true,
    },
    {
      title: '性别',
      dataIndex: 'sex',
      width: axconst.width.two,
      ellipsis: true,
      render: val => <AxColumnEnum enumName='sex' value={val} />,
    },
    {
      title: '身份证',
      dataIndex: 'idcard',
      width: axconst.width.idcard,
      ellipsis: true,
    },
    {
      title: '联系电话',
      dataIndex: 'phone',
      width: axconst.width.phone,
      ellipsis: true,
    },
  ];

  return (
    <AxModal
      {...rest}
      showLoading={false}
      footer={false}
      visible={visible}
      width="50%"
      handleVisible={handleVisible}
      items={[
        <Row gutter={12}>
          <Col span={14}>
            <Search
              placeholder={placeholder ? placeholder : "搜索"}
              onSearch={val => handleSearch(val)}
              defaultValue={searchValue}
              style={{ width: '100%' }}
              allowClear
            />
            <div className={styles.demoInfiniteContainer}>
              <InfiniteScroll
                initialLoad={false}
                pageStart={0}
                loadMore={() => { }}
                useWindow={false}
              >
                <Table
                  rowKey={record => record.id}
                  checkboxModel={false}
                  columns={columns}
                  dataSource={data.list}
                  loading={loading}
                  pagination={false}
                  onRow={record => ({
                    onDoubleClick: () => {
                      handleClickRow(record);
                    },
                  })}
                />
              </InfiniteScroll>
            </div>
            <Pagination
              size="small"
              style={{ float: 'right', marginTop: '5px' }}
              pageSize={page.pageSize}
              total={data.pagination.total}
              onChange={handlePageChange}
            />
          </Col>
          <Col span={10}>
            <h3>快速添加缴费人</h3>
            <AxInput
              form={form}
              label="姓名"
              field="name"
              required
            />
            <AxInput
              form={form}
              label="身份证"
              field="idcard"
              pattern={axconst.valid.idCard}
            />
            <AxInput
              form={form}
              label="联系电话"
              field="phone"
              pattern={axconst.valid.mobile}
              required
            />
            <AxInput
              form={form}
              label="微信"
              field="weiXin"
            />
            <AxInput
              form={form}
              label="QQ"
              field="qq"
            />
            <div style={{ float: 'right' }}>
              <Button onClick={handleReset}>
                重填
              </Button>
              <Button
                type='primary'
                style={{ marginLeft: 8 }}
                loading={confirmLoading}
                onClick={handleCreate}
              >
                保存
              </Button>
            </div>
          </Col>
        </Row>,
      ]}
    ></AxModal>
  );
};

export default Form.create()(AxSelectPayer);
